package com.lgy.springboot_example.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter,
                                            MessageListenerAdapter listenerAdapter2) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //订阅了一个叫chat 的通道,可以添加多个 messageListener
        container.addMessageListener(listenerAdapter, new PatternTopic("myChat"));
        container.addMessageListener(listenerAdapter2, new PatternTopic("myChat-2"));
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(RedisMsgReceiver receiver) {
        //第二个参数为RedisMsgReceiver里面的方法名
        return new MessageListenerAdapter(receiver, "receiverMsg");
    }

    @Bean
    MessageListenerAdapter listenerAdapter2(RedisMsgReceiver receiver) {
        //第二个参数为RedisMsgReceiver里面的方法名
        return new MessageListenerAdapter(receiver, "receiverMsg2");
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }

    //配置redis序列化方式
    @Bean
    public <T> RedisTemplate<String, T> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, T> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
}
